/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useEffect, useCallback, useMemo } from "react";
import PageHeaderLayout from "@/layouts/PageHeaderLayout";
import StandardTable from "@/components/StandardTable";
import {
  Form,
  Select,
  DatePicker,
  Popconfirm,
  Row,
  Col,
  Button,
  Input,
  Modal,
  message,
} from "antd";
import { useAntdTable } from "ahooks";
import patterns from "@/utils/patterns";
import { connect } from "dva";
import moment from "moment";
import PopoverInfo from "@/components/PopoverInfo";
import HelpAndService from "@/components/HelpAndService";
import { getLStorage } from "@/utils/utils";
import { cloneDeep } from "lodash";
import BrandsSelect from "./components/BrandsSelect";
import ExportList from "./components/ExportList";
import AllotPop from "./components/AllotPop";
import ColumnsSetting from "./components/ColumnsSetting";
import { getOrderDetailsList, fixOrderDetailFormData } from "../utils/orderDetail";
import commstyle from "../commen.less";
import styles from "./index.less";

const { containerBox } = styles;
const { TextArea } = Input;
const { RangePicker } = DatePicker;
const { Option, OptGroup } = Select;
const dateFormat = "YYYY-MM-DD HH:mm:ss";
const { phone } = patterns;
const hiddenStyle = { style: { display: "none" } };
const formItemLayout = {
  labelCol: { xs: { span: 0 }, sm: { span: 6 } },
  wrapperCol: { xs: { span: 24 }, sm: { span: 18 } },
};
const sourceOptions = [
  {
    lable: "业务员类",
    options: [
      { lable: "微快递-业务员", value: 1 },
      { lable: "微掌柜-业务员", value: 2 },
      { lable: "小邮筒-业务员", value: 3 },
      { lable: "自建订单-业务员", value: 4 },
      { lable: "定制公众号-业务员", value: 5 },
      { lable: "定制小程序-业务员", value: 6 },
      { lable: "网页版-业务员", value: 7 },
    ],
  },
  {
    lable: "快宝驿站类",
    options: [
      { lable: "小邮筒-快宝驿站", value: 8 },
      { lable: "快宝驿站公众号/小程序-快宝驿站", value: 9 },
      { lable: "定制公众号-快宝驿站", value: 10 },
      { lable: "定制小程序-快宝驿站", value: 11 },
      { lable: "网页版-快宝驿站", value: 12 },
      { lable: "自建订单-快宝驿站", value: 13 },
    ],
  },
  {
    lable: "待分配类",
    options: [
      { lable: "定制小程序-待分配订单", value: 14 },
      { lable: "定制公众号-待分配订单", value: 15 },
      { lable: "全部待分配订单", value: 16 },
    ],
  },
  {
    lable: "待收款类",
    options: [{ lable: "全部待收款订单", value: 17 }],
  },
];

const ranges = {
  今天: [moment(), moment()],
  昨天: [
    moment()
      .startOf("day")
      .subtract(1, "days"),
    moment()
      .startOf("day")
      .subtract(1, "days"),
  ],
  "30天": [
    moment()
      .startOf("day")
      .subtract(30, "days"),
    moment()
      .startOf("day")
      .subtract(0, "days"),
  ],
};
const disabledDate = current => {
  return current && current > moment().endOf("day");
};

const rowSelection = {
  hideDefaultSelections: true,
  fixed: true,
};

const Index = ({
  orderDetailList,
  dispatch,
  location,
  form: { getFieldDecorator, setFieldsValue },
  form,
  options: { key },
  user_info,
}) => {
  const {
    query: { orderStatus = "", orderSource = undefined },
  } = location;
  const { branchId, shop_id } = user_info;
  const isZyAccount = key === "post";
  const data = orderStatus ? { orderStatus, orderSource } : {};
  const defaultPagination = {
    current: 1,
    pageSize: getLStorage(`${shop_id}orderDetailPageSize`) || 10,
  };

  /**
   * 初始columns
   *  */
  const columns = useMemo(
    () => [
      {
        title: () => <a onClick={() => setVisible(true)}>设置</a>,
        dataIndex: "num",
        key: "num",
        width: 100,
        fixed: "left",
        align: "center",
      },
      {
        title: "订单信息",
        dataIndex: "order_info",
        width: 200,
        align: "center",
        render: (_, record) => {
          return (
            <div>
              <p>{record.id}</p>
              <p>{record.chann}</p>
            </div>
          );
        },
      },
      { title: "快递品牌", width: 100, dataIndex: "brand" },
      {
        title: "寄件信息",
        dataIndex: "sendInfo",
        width: 200,
        render(_, record) {
          return (
            <div>
              <p>
                姓名：
                {record.shipper_name}
              </p>
              <p>
                电话：
                {record.shipper_mobile}
              </p>
              <p>
                地址：
                {record.shipper_city + record.shipper_district + record.shipper_address}
              </p>
            </div>
          );
        },
      },
      {
        title: "收件信息",
        dataIndex: "getInfo",
        width: 200,
        render(_, record) {
          return (
            <div>
              <p>
                姓名：
                {record.shipping_name}
              </p>
              <p>
                电话：
                {record.shipping_mobile}
              </p>
              <p>
                地址：
                {record.shipping_city + record.shipping_district + record.shipping_address}
              </p>
            </div>
          );
        },
      },
      {
        title: "处理方",
        dataIndex: "courierInfo",
        width: 200,
        render: (_, record) => {
          const { shipping_area_id, collect_courier_name, collect_courier_mobile } = record;
          const title = shipping_area_id == 0 ? "业务员：" : "驿站：";
          return (
            <>
              <div>
                {title}
                {collect_courier_name || "-"}
              </div>
              <div>{collect_courier_mobile || "-"}</div>
            </>
          );
        },
      },
      {
        title: "时间节点",
        dataIndex: "update_at",
        width: 200,
        render: (update_at, record) => {
          const { status, create_at } = record;
          return (
            <>
              <div>接单时间：</div>
              <div>{create_at}</div>
              {status > 2 && (
                <>
                  <div>打印时间：</div>
                  <div>{update_at}</div>
                </>
              )}
            </>
          );
        },
      },
      { title: "物品类型", dataIndex: "package_info", width: 100 },
      { title: "备注", dataIndex: "package_note", width: 200 },
      {
        title: "订单状态",
        dataIndex: "statusText",
        width: 200,
      },
      {
        title: "运单号",
        dataIndex: "waybill_no",
        width: 200,
        render: (_, record) => {
          return (
            <>
              <div>{record.waybill_no || "暂无"}</div>
              {record.pickup_code && (
                <div>
                  揽件码：
                  {record.pickup_code}
                </div>
              )}
            </>
          );
        },
      },
      {
        title: "优惠信息",
        width: 200,
        dataIndex: "iscountAmount",
        render: iscountAmount => {
          const { money, type } = iscountAmount || {};
          return (
            <>
              <p>
                类型：
                {type || "暂无"}
              </p>
              <p>
                金额：
                {money || "暂无"}
              </p>
            </>
          );
        },
      },
      {
        title: "结算重量",
        width: 100,
        dataIndex: "charging_weight",
        align: "center",
        render: charging_weight => `${charging_weight || 0} kg`,
      },
      {
        title: "支付信息",
        width: 250,
        dataIndex: "payInfo",
        render: payInfo => {
          const { money, status, type, time } = payInfo;
          return (
            <>
              <p>
                金额：
                {money || "暂无"}
              </p>
              <p>
                状态：
                {status || "暂无"}
              </p>
              <p>
                类型：
                {type || "暂无"}
              </p>
              <p>
                时间：
                {time || "暂无"}
              </p>
            </>
          );
        },
      },
      {
        title: "操作",
        fixed: "right",
        width: 100,
        render: (_, record) => {
          const hideBtn = !!record.waybill_no || record.statusText == "已取消";
          if (hideBtn) return;
          return (
            <div>
              <div>
                <Popconfirm title="确定关闭该订单？" onConfirm={() => handleCloseOrder(record.id)}>
                  <Button type="danger">关闭订单</Button>
                </Popconfirm>
              </div>
              <div>
                <Button
                  type="primary"
                  style={{ marginTop: 10 }}
                  onClick={() => handleOrderAllocation(record)}
                >
                  分配订单
                </Button>
              </div>
            </div>
          );
        },
      },
    ],
    [handleCloseOrder]
  );

  const [orderSourceInState, setOrderSourceInState] = useState(orderSource);
  const [tableFormData, updateTableFormData] = useState({
    formData: {
      orderStatus,
      orderSource,
    },
    pagination: defaultPagination,
  });
  const [taskTableVisible, upTaskTableVisible] = useState(false);
  const [allotPopVisible, setAllotPopVisible] = useState(false);
  const [selectedRows, setSelectedRows] = useState(null);
  const [record, setRecord] = useState({});
  const [action, upAction] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [courierList, setCourierList] = useState([]);
  const [visible, setVisible] = useState(false);
  const [sortedColumn, setSortedColumn] = useState(columns || []);

  const getTableData = (pagination, formData) => {
    const { current, pageSize } = pagination || {};
    setCurrentPage(current);
    updateTableFormData({ formData, pagination });
    return getOrderDetailsList({ formData, current: current || "", pageSize }, dispatch);
  };

  const { tableProps, search, loading } = useAntdTable(getTableData, {
    form,
    defaultParams: [
      defaultPagination,
      {
        ...data,
      },
    ],
  });

  const { submit, reset } = search;

  const handleOrderAllocation = data => {
    setAllotPopVisible(true);
    setRecord(data);
  };

  const handleCancelSel = () => {
    setSelectedRows(null);
  };

  const handleSelectRows = rows => {
    setSelectedRows(rows);
  };

  const handleBatchSelect = action => {
    upAction(action);
    setSelectedRows([]);
  };

  const handleActionPlay = type => {
    const { length } = selectedRows;
    if (!length || length <= 0) {
      message.error("请至少选择一项进行操作！");
      return;
    }
    const ids = selectedRows.map(i => i.id).join(",");

    switch (type) {
      case "close":
        closeOrder(ids);
        break;
      case "apportion":
        setAllotPopVisible(true);
        setRecord({});
        break;
      default:
        break;
    }
  };

  const handleCloseOrder = useCallback(
    id => {
      closeOrder(id);
    },
    [closeOrder]
  );

  const closeOrder = useCallback(
    ids => {
      dispatch({ type: "orderDetails/closeOrder", payload: { order_id: ids } }).then(() => {
        const { formData } = tableFormData;
        handleCancelSel();
        getOrderDetailsList({ formData, current: currentPage, pageSize: 10 }, dispatch);
      });
    },
    [currentPage, dispatch, tableFormData]
  );

  const addExportTask = () => {
    const { formData, pagination } = tableFormData;
    const { timeRange } = formData;
    if (!timeRange) {
      message.error("请先选择下单时间范围再添加导出任务");
      return;
    }
    const data = fixOrderDetailFormData({ formData, ...pagination });
    dispatch({ type: "orderDetails/addExportOrderTask", payload: { ...data } });
  };

  const handleTaskModalClose = () => {
    upTaskTableVisible(false);
  };

  const handleOpenTaskTable = () => {
    upTaskTableVisible(true);
  };

  const onReset = () => {
    setFieldsValue({
      orderSource: undefined,
    });
    setOrderSourceInState(undefined);
    reset();
  };

  const changeColumns = useCallback(
    () => {
      const localColumns = getLStorage(`${shop_id}orderDetailColumns`);
      if (!localColumns) return;
      const clonedColumn = cloneDeep(columns);
      const columnKeys = clonedColumn.filter(v => !v.fixed).map(i => i.dataIndex);
      const sortedColumns = [];
      // 使用设置好的column来循环，防止排列顺序不对
      localColumns.forEach(({ selected, key: selectKey }) => {
        if (selected && columnKeys.includes(selectKey)) {
          const selectedItem = clonedColumn.find(item => item.dataIndex === selectKey);
          sortedColumns.push(selectedItem);
        }
      });
      // 添加原有columns的收尾两项
      setSortedColumn([clonedColumn[0], ...sortedColumns, clonedColumn[clonedColumn.length - 1]]);
    },
    [columns, shop_id]
  );

  useEffect(
    () => {
      changeColumns();
      dispatch({
        type: "clientManage/getCascaderInfo",
      }).then(list => {
        setCourierList(list);
      });
    },
    [dispatch, changeColumns]
  );

  return (
    <PageHeaderLayout
      title={
        <Row type="flex" justify="space-between">
          <Col>
            订单明细
            <PopoverInfo placement="bottomLeft">
              <p>
                <strong>订单信息：</strong>
                订单号/订单创建渠道/揽件对象类型
              </p>
              <p>
                <strong>快递品牌：</strong>
                用户下单品牌
              </p>
              <p>
                <strong>寄件信息： </strong>
                寄件人信息
              </p>
              <p>
                <strong>收件信息：</strong>
                收件人信息
              </p>
              <p>
                <strong>处理方：</strong>
                业务员名称和账号+站点/驿站名字+账号/无站点业务员，不显示
              </p>
              <p>
                <strong>时间节点：</strong>
                未打印，只显示接单时间/已打印， 显示接单时间和打印时间上下两列
              </p>
              <p>
                <strong>物品：</strong>
                用户下单时选择的物品类型
              </p>
              <p>
                <strong>备注：</strong>
                用户下单时填写的备注
              </p>
              <p>
                <strong>订单状态：</strong>
                已下单、已受理、已发货、运输中、 派件中、已签收、已取消、待付款、待分配
              </p>
              <p>
                <strong>运单号：</strong>
                已下单未打印显示暂无及揽件码/获取单号后，显示运单号
              </p>
              <p>
                <strong>优惠信息：</strong>
                显示用户使用的优惠信息和折扣金额，现有优惠券和积分两个类型
              </p>
              <p>
                <strong>结算重量：</strong>
                用户手填重量，如果是申通品牌订单，额外多显示一行梧桐重量
              </p>
              <p>
                <strong>支付信息：</strong>
                支付金额 （具体金额数量）/
                支付状态（已支付/待支付)/类型（下单现付/推送运费/二维码收款/权益次卡抵扣）
                <br />
                注：权益次卡抵扣如有续付运费显示为 权益次卡抵扣+另付5元 ，如果没有续付运费只显示为
                权益次卡抵扣
              </p>
            </PopoverInfo>
          </Col>
          <Col>
            <HelpAndService />
          </Col>
        </Row>
      }
    >
      <div className={commstyle.main}>
        <Form onSubmit={submit}>
          <Row>
            <Col span={18}>
              <Row>
                <Col span={12}>
                  <Form.Item {...formItemLayout} label="订单来源">
                    {getFieldDecorator("orderSource", {
                      initialValue: isNaN(orderSourceInState) ? "all" : orderSourceInState * 1,
                    })(
                      <Select placeholder="请选择订单来源" allowClear>
                        <Option value="all">全部</Option>
                        {sourceOptions.map(item => {
                          const { lable, options } = item;
                          return (
                            <OptGroup key={lable} label={lable}>
                              {options.map(option => (
                                <Option key={option.value} value={option.value}>
                                  {option.lable}
                                </Option>
                              ))}
                            </OptGroup>
                          );
                        })}
                      </Select>
                    )}
                  </Form.Item>
                  <Form.Item {...formItemLayout} label="寄件人电话">
                    {getFieldDecorator("sendPhone", {
                      rules: [
                        {
                          ...phone,
                        },
                      ],
                    })(<Input placeholder="寄件人电话" style={{ width: "100%" }} />)}
                  </Form.Item>
                  <Form.Item {...formItemLayout} label="下单时间">
                    {getFieldDecorator("timeRange")(
                      <RangePicker
                        ranges={ranges}
                        format={dateFormat}
                        style={{ width: "100%" }}
                        showTime
                        disabledDate={disabledDate}
                      />
                    )}
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item {...formItemLayout} label="订单状态">
                    {getFieldDecorator("orderStatus", {
                      initialValue: "2",
                    })(
                      <Select placeholder="请选择订单状态">
                        <Option value="all">全部</Option>
                        <Option value="2">已受理</Option>
                        <Option value="3">已发货</Option>
                        <Option value="4">运输中</Option>
                        <Option value="5">派件中</Option>
                        <Option value="6">已签收</Option>
                        <Option value="7">已取消</Option>
                      </Select>
                    )}
                  </Form.Item>
                  <Form.Item {...formItemLayout} label="收件人电话">
                    {getFieldDecorator("getPhone", {
                      rules: [
                        {
                          ...phone,
                        },
                      ],
                    })(<Input placeholder="收件人电话" style={{ width: "100%" }} />)}
                  </Form.Item>
                  <Form.Item {...formItemLayout} label="快递品牌">
                    {getFieldDecorator("brand")(
                      <BrandsSelect allowClear style={{ width: "100%" }} />
                    )}
                  </Form.Item>
                </Col>
              </Row>
            </Col>
            <Col span={6}>
              <Row type="flex" justify="center" align="middle">
                <Col span={20}>
                  {getFieldDecorator("orderId")(
                    <TextArea
                      allowClear
                      style={{ height: "160px", resize: "none" }}
                      placeholder="请输入运单号，多个编号按回车"
                    />
                  )}
                </Col>
              </Row>
            </Col>
          </Row>
          <Row type="flex" justify="space-between">
            <Col>
              <Row>
                <Col>
                  <Row type="flex" gutter={[20, 0]}>
                    <Col>
                      <Button type="primary" onClick={() => handleBatchSelect("close")}>
                        批量关闭
                      </Button>
                    </Col>
                    <Col>
                      <Button onClick={() => handleBatchSelect("apportion")} type="primary">
                        批量分配
                      </Button>
                    </Col>
                  </Row>
                </Col>
              </Row>
            </Col>
            <Col>
              <Row type="flex">
                <Col>
                  <Button style={{ marginRight: 20 }} onClick={onReset}>
                    重置
                  </Button>
                  <Button type="primary" htmlType="submit" loading={loading}>
                    查询
                  </Button>
                </Col>
              </Row>
            </Col>
          </Row>
        </Form>
        <div className={containerBox}>
          <StandardTable
            rowKey="id"
            scroll={{ x: 2300 }}
            onSelectRow={handleSelectRows}
            selectedRows={selectedRows}
            columns={sortedColumn}
            rowSelection={rowSelection}
            data={orderDetailList}
            {...tableProps}
          />
          {selectedRows ? (
            <Row type="flex" justify="center">
              <Col>
                {action == "close" ? (
                  <Popconfirm title="确认批量关闭？" onConfirm={() => handleActionPlay(action)}>
                    <Button type="primary" style={{ marginRight: "10px" }}>
                      批量关闭
                    </Button>
                  </Popconfirm>
                ) : (
                  <Button
                    type="primary"
                    style={{ marginRight: "10px" }}
                    onClick={() => handleActionPlay(action)}
                  >
                    分配订单
                  </Button>
                )}

                <Button type="primary" onClick={handleCancelSel}>
                  取消
                </Button>
              </Col>
            </Row>
          ) : (
            ""
          )}
          <AllotPop
            id={selectedRows ? selectedRows.map(i => i.id) : [record.id]}
            onVisible={setAllotPopVisible}
            visible={allotPopVisible}
            record={record}
            getList={() =>
              getOrderDetailsList(
                { formData: tableFormData.formData, current: currentPage, pageSize: 10 },
                dispatch
              )
            }
            courierList={courierList}
            isZyAccount={isZyAccount}
            branchId={branchId}
          />
        </div>
        <Modal
          visible={taskTableVisible}
          onCancel={handleTaskModalClose}
          onOk={handleTaskModalClose}
          destroyOnClose
          cancelButtonProps={hiddenStyle}
          okText="关闭"
        >
          <ExportList />
        </Modal>
        <ColumnsSetting
          visible={visible}
          setColumns={changeColumns}
          handleVisible={setVisible}
          shop_id={shop_id}
        />
      </div>
    </PageHeaderLayout>
  );
};

export default connect(({ orderDetails, user, setting }) => ({
  orderDetailList: orderDetails.orderDetailList,
  user_info: user.currentUser.user_info,
  ...setting,
}))(Form.create()(Index));
